<template>
  <Loader :loading="loading">
    <view class="flex-col group">
      <view class="flex-col section_4">
        <view class="flex-row items-center">
          <image class="image_7" src="/static/icon/notice_pink.svg" />
          <text class="font_2 text_3 ml-5">说明：</text>
        </view>
        <text class="font text_4 mt-7">经过以上筛查，我们建议您完成以下问卷，以让我们更好地了解您：</text>
      </view>
      <progress show-info font-size="12" class="progress mt-12" :percent="progress" activeColor="#F26A77"
        backgroundColor="#FFFFFF" border-radius="8" active active-mode="forwards" duration="20" />
      <view class="flex-col items-center mt-12">
        <scroll-view class="flex-col assesscard-container" scroll-y enable-flex>
          <assess-card class="section_7 mt-10" v-for="item in assessItems" :key="item.id" :item="item"
            :done="doneList[item.id]" @clearAssess="bindClearAssess" @finishAssess="bindFinishAssess"></assess-card>
        </scroll-view>
        <button class="mt-12" :class="allDone ? 'button-done' : 'button-undone'" hover-class="button-hover"
          :disabled="!allDone" @click="submit">
          {{ allDone ? "提交" : "未完成" }}
        </button>
      </view>
    </view>
  </Loader>
</template>

<script>
import { getAssessConfig, getCompressor, generateTags, saveResults } from "../../util/questionnaire/index.js";
import { AssessCard } from "../../components/Questionnare/AssessCard/AssessCard.vue";
import Loader from "../../../components/Loader/Loader.vue";
import { storage } from "@/util/storage.js";
export default {
  components: {
    AssessCard,
    Loader,
  },
  data() {
    const assessConfig = getAssessConfig();
    return {
      loading: false,
      scResults: [],
      asResults: {},
      assessIndex: assessConfig.mapping,
      assessDetails: assessConfig.detail,
      asResultDetails: {},
    };
  },
  methods: {
    bindFinishAssess(res) {
      this.asResults[res.id] = res.result;
      // 存储每个问卷的详情
      if (res.details) {
        this.asResultDetails[res.id] = res.details;
        this.$storage.set("assess_details", this.asResultDetails);
      }
      console.log("finish assess: ", this.asResults);
      console.log("assess details: ", this.asResultDetails);
      this.$storage.set("assess_results", this.asResults);
    },
    bindClearAssess(res) {
      delete this.asResults[res.id];
      // 同时清除对应的详情
      delete this.asResultDetails[res.id];
      this.$storage.set("assess_results", this.asResults);
      this.$storage.set("assess_details", this.asResultDetails);
      console.log("clear assess: ", this.asResults);
      console.log("clear assess details: ", this.asResultDetails);
    },
    submit() {
      console.log("submit: ", this.asResults);
      const asResultJson = JSON.stringify(this.asResults);
      console.log("result json: ", asResultJson);
      const tags = generateTags('assessment', this.asResults);
      const compressor = getCompressor('assessment');
      const compressed = compressor.compress(this.asResults);
      console.log("compressed: ", compressed);
      console.log("compressed string: ", JSON.stringify(compressed));
      console.log("generated tags:", tags);
      // merge details
      const mergedDetails = {};
      for (const key in this.asResultDetails) {
        for (const detail in this.asResultDetails[key]) {
          if (mergedDetails[detail]) {
            console.warn("detail already exists: ", detail);
          }
          mergedDetails[detail] = this.asResultDetails[key][detail];
        }
      }
      saveResults({
        type: 'assessment',
        result: compressed,
        details: mergedDetails,
        tags: tags,
        success: (res) => {
          console.log("submit result: ", res);
          uni.showToast({ title: "提交成功", icon: "success" });
          uni.redirectTo({ url: "../assess_result/assess_result" });
        },
        fail: (err) => {
          uni.showToast({ title: "提交失败", icon: "none" });
          console.error("提交失败", err);
        }
      })
    },
  },
  computed: {
    assessItems() {
      if (!this.scResults) return [];
      const asItems = [];
      for (const item of this.scResults)
        if (item.risk)
          asItems.push(this.assessDetails[this.assessIndex[item.id]]);
      console.log("asItems: ", asItems);
      return asItems;
    },
    doneList() {
      const doneList = {};
      for (const item of this.assessDetails) {
        if (this.asResults.hasOwnProperty(item.id)) {
          doneList[item.id] = true;
        } else {
          doneList[item.id] = false;
        }
      }
      return doneList;
    },
    allDone() {
      for (const item of this.assessItems) {
        if (!this.doneList[item.id]) return false;
      }
      return true;
    },
    progress() {
      return Math.round(
        (Object.keys(this.asResults).length / this.assessItems.length) * 100
      );
    },
  },
  async mounted() {
    this.loading = true;
    // get from local storage
    try {
      const asResults = this.$storage.get("assess_results");
      const asResultDetails = this.$storage.get("assess_details");
      if (asResults) this.asResults = asResults;
      if (asResultDetails) this.asResultDetails = asResultDetails;

      const res = await this.$request({ 
        url: '/survey/get/', 
        method: 'GET',
        data: { type: 'screening' } 
      });
      
      if (res && res.statusCode === 200 && res.data && res.data.result) {
        const result = res.data.result.result;
        const compressor = getCompressor('screening');
        this.scResults = compressor.decompress(result);
        console.log("Fetched screening results from backend:", this.scResults);
      } else {
        throw "Failed to fetch screening results from backend";
      }
    } catch (e) {
      console.log(e);
      uni.navigateBack();
    }
    console.log("get screening results: ", this.scResults);
    
    this.loading = false;
  },
};
</script>

<style scoped>
.ml-5 {
  margin-left: 10rpx;
}

.mt-7 {
  margin-top: 14rpx;
}

.mt-11 {
  margin-top: 22rpx;
}

.font {
  font-size: 32rpx;
  color: #000000;
}

.group {
  padding: 24rpx 33rpx 0;
}

.section_4 {
  padding: 16rpx 24rpx 15.86rpx;
  background-color: #ffffff;
  border-radius: 24rpx;
}

.image_7 {
  width: 48rpx;
  height: 48rpx;
}

.font_2 {
  font-size: 32rpx;
  line-height: 30.84rpx;
  font-weight: 700;
  color: #000000;
}

.text_3 {
  font-size: 30rpx;
  line-height: 29.44rpx;
}

.text_4 {
  line-height: 38rpx;
}

.section_5 {
  margin-top: 24rpx;
}

.view {
  background-color: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
}

.section_6 {
  background-color: #f26a77;
  border-radius: 16rpx;
  width: 480rpx;
  height: 12rpx;
}

.assesscard-container {
  border-radius: 24rpx;
  overflow: hidden;
  border-top: solid 2rpx #e4e4e4;
  border-bottom: solid 2rpx #e4e4e4;
  max-height: 1000rpx;
}

.section_7 {
  margin-right: 4rpx;
}

.section_7:first-child {
  margin-top: 0;
}

.text-wrapper_2 {
  padding: 26.58rpx 0 26.48rpx;
  background-color: #979797;
  border-radius: 24rpx;
}

.text_10 {
  color: #ffffff;
  font-size: 40rpx;
  font-weight: 700;
  line-height: 38.94rpx;
}

.button-undone {
  width: 680rpx;
  border-radius: 24rpx;
  background-color: #979797 !important;
  color: #ffffff !important;
}

.button-done {
  width: 680rpx;
  border-radius: 24rpx;
  background-color: #f26a77;
  color: #ffffff;
}

.button-hover {
  background-color: #e56571;
}
</style>

<style>
page {
  background-color: #f5f5f5;
}
</style>
